;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Report.HostFinanceReportCostAnaly", [])
        .controller("HostFinanceReportCostAnalyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, $stateParams) {
           
            var currentDate = new Date();

            $scope.company = {
                // 分页信息
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                // 搜索条件
                condition: {
                    startCreateDate: new Date(currentDate.getFullYear(), currentDate.getMonth(),1),
                    endCreateDate: currentDate
                },
                // 时间展示和隐藏
                datePickerFlag: [false, false],
                // 切换时间展示和隐藏
                switchDataPicker: function (index) {
                    $scope.company.datePickerFlag = [false, false];
                    if (angular.isDefined(index)) {
                        $scope.company.datePickerFlag[index] = true;
                    }
                }
            }; 
            $scope.warehouse = {
                // 分页信息
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                // 搜索条件
                condition: {
                    startCreateDate: new Date(currentDate.getFullYear(), currentDate.getMonth(),1),
                    endCreateDate: currentDate
                },
                // 时间展示和隐藏
                datePickerFlag: [false, false],
                // 切换时间展示和隐藏
                switchDataPicker: function (index) {
                    $scope.warehouse.datePickerFlag = [false, false];
                    if (angular.isDefined(index)) {
                        $scope.warehouse.datePickerFlag[index] = true;
                    }
                },
                // 汇总的数据
                totalRow: []
            }; 

            // 数据列表
            $scope.dataList = [];

            // 表格配置
            $scope.tbConf = {};

            // 构造多级表格头
            function setTableHead(isWarehouse) {
                var TdWidth = 120; // 表格列宽度
                var mockRes = [
                    {
                        materialCalssName: '入库',
                        isShow: true,
                        materialClassVOList: [
                            { materialCalssName: '主机厂', dataField: 'mainFactoryInAmount', isShow: true },
                            { materialCalssName: '外采', dataField: 'purchaseInAmount', isShow: true },
                            { materialCalssName: '代理商间调拨', dataField: 'agentAllotInAmount', isShow: true },
                            { materialCalssName: '退货单', dataField: 'agentReturnInAmount', isShow: true },
                            { materialCalssName: '借用退回单', dataField: 'borrowInAmount', isShow: true },
                            { materialCalssName: '区域调拨', dataField: 'regionAllotInAmount', isShow: isWarehouse },
                            { materialCalssName: '其他', dataField: 'abnormalInAmount', isShow: true },
                            { materialCalssName: '小计', dataField: 'inSubTotal', isShow: true },
                        ]
                    },
                    {
                        materialCalssName: '出库',
                        isShow: true,
                        materialClassVOList: [
                            { materialCalssName: '现金', dataField: 'cashOutAmount', isShow: true },
                            { materialCalssName: '赠送', dataField: 'presentOutAmount', isShow: true },
                            { materialCalssName: '三包', dataField: 'threeOutAmount', isShow: true },
                            { materialCalssName: '超保', dataField: 'overServiceOutAmount', isShow: true },
                            { materialCalssName: '代理商间调拨', dataField: 'agentAllotOutAmount', isShow: true },
                            { materialCalssName: '服务借用单', dataField: 'borrowOutAmount', isShow: true },
                            { materialCalssName: '区域调拨', dataField: 'regionAllotOutAmount', isShow: isWarehouse },
                            { materialCalssName: '其他', dataField: 'abnormalOutAmount', isShow: true },
                            { materialCalssName: '小计', dataField: 'outSubTotal', isShow: true },
                        ]
                    }
                ]
                var firstTableCol = [];
                var secondTableCol = [];
                angular.forEach(mockRes, function (item) {
                    if (item.isShow && item.materialClassVOList.length > 0) {
                        var isShowNum = 0;
                        angular.forEach(item.materialClassVOList, function (second) {
                            if (second.isShow) {
                                isShowNum ++;
                                secondTableCol.push({
                                    name: second.materialCalssName,
                                    width: TdWidth,
                                    dataField: second.dataField
                                });
                            }
                        });
                        firstTableCol.push({
                            name: item.materialCalssName,
                            width: TdWidth * isShowNum,
                            colSpan: isShowNum
                        });
                    }
                });
                var fixWidth = isWarehouse ? 100 + 160 + 120 : 200 + 120
                $scope.tbConf.scrollWidth = TdWidth * secondTableCol.length + fixWidth;
                $scope.tbConf.firstTableCol = firstTableCol;
                $scope.tbConf.secondTableCol = secondTableCol;
            }

            // 搜索供货关系列表(公司层)
            $scope.companySearch = function (curPage) {
                $scope.dataList = [];
                var reqUrl = "/report/agentFinanceCompanyList";
                if (!!curPage) {
                    $scope.company.pageInfo.curPage = curPage;
                }
                var param = {
                    pageNum: $scope.company.pageInfo.curPage,
                    pageSize: $scope.company.pageInfo.pageSize,
                    filters: angular.copy($scope.company.condition)
                };
                ybHttp.Post('device', reqUrl, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    if (!res.value) return;
                    $scope.company.pageInfo.totalRows = res.value.total;
                    $scope.company.pageInfo.totalPages = res.value.pages;
                    angular.forEach(res.value.list, function(item) {
                        if (!item.finanaceAmountList) {
                            item.finanaceAmountList = [{statisticType: '数量'}, {statisticType: '金额'}];
                        }
                    })
                    $scope.dataList = res.value.list;
                });
            };

            // 搜索供货关系列表(仓库层)
            $scope.warehouseSearch = function (curPage) {
                $scope.dataList = [];
                var reqUrl = "/report/agentFinanceWarehouseList";
                if (!!curPage) {
                    $scope.warehouse.pageInfo.curPage = curPage;
                }
                var param = {
                    pageNum: $scope.warehouse.pageInfo.curPage,
                    pageSize: $scope.warehouse.pageInfo.pageSize,
                    filters: angular.copy($scope.warehouse.condition)
                };
                ybHttp.Post('device', reqUrl, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    if (!res.value) return;
                    
                    $scope.warehouse.totalRow = res.value.list.splice(0, 1);

                    angular.forEach(res.value.list, function(dataItem) {
                        angular.forEach(dataItem.warehouseList, function(warehouseItem, warehouseIdx) {
                            angular.forEach(warehouseItem.finanaceAmountList, function(finanaceItem, finanaceIdx) {
                                if (warehouseIdx === 0 && finanaceIdx === 0) {
                                    // 代理商的第一个仓库,第一个统计行（数量）：展示代理商名称
                                    finanaceItem.showAgent = true
                                    finanaceItem.agentName = dataItem.agentName;
                                    finanaceItem.agentRowSpan = dataItem.warehouseList.length * warehouseItem.finanaceAmountList.length
                                }
                                if (finanaceIdx === 0) {
                                    // 仓库的第一个统计行（数量）：展示仓库名称
                                    finanaceItem.showWarehouse = true
                                    finanaceItem.warehouseName = warehouseItem.warehouseName;
                                    finanaceItem.warehouseRowSpan = warehouseItem.finanaceAmountList.length
                                }
                                $scope.dataList.push(finanaceItem)
                            })
                        })
                    })
                    if ($scope.dataList.length === 0) {
                        $scope.warehouse.pageInfo.totalRows = 0;
                        $scope.warehouse.pageInfo.totalPages = 1;
                    } else {
                        $scope.warehouse.pageInfo.totalRows = res.value.total;
                        $scope.warehouse.pageInfo.totalPages = res.value.pages;
                    }
                });
            };

            $scope.changeTab = function (index) {
                switch(index) {
                    case 0:
                        setTableHead();
                        $scope.companySearch(1);
                        break;
                    case 1:
                        setTableHead(true);
                        $scope.warehouseSearch(1);
                        break;
                    default:
                        break;
                }
            }

            // 检查日期
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            (function () {
                setTableHead();
                $scope.companySearch(1);
            })();
        }])
        ;
})(window, window.angular);